package services;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import repositories.AdministratorRepository;
import domain.Administrator;
import forms.RegisterForm;

@Transactional
@Service
public class AdministratorService {

	// Managed repository

	@Autowired
	private AdministratorRepository administratorRepository;
	
	
	// Supporting services
	
	@Autowired
	private ActorService actorService;

	// Simple CRUD methods

	public Administrator create() {
		return new Administrator();
	}

	public void save(Administrator administrator) {
		Md5PasswordEncoder encoder = new Md5PasswordEncoder(); 
		Assert.notNull(administrator);
		Assert.isTrue(actorService.findByPrincipal() instanceof Administrator);
		
		String oldPassword = administrator.getUserAccount().getPassword();
		
		Administrator existingAdmin = administratorRepository.findAdminByUsername(administrator.getUserAccount().getUsername());
		
		Assert.isNull(existingAdmin, "register.duplicated.username");
		
		administrator.getUserAccount().setPassword(encoder.encodePassword(oldPassword, null));

		administratorRepository.save(administrator);
	}
	
	public Administrator reconstruct(RegisterForm registerForm)
	{
		Assert.isTrue(registerForm.getTerminos(),"register.commit.terms.error");
		Assert.isTrue(registerForm.getUserAccount().getPassword().equals(registerForm.getRepeatPass()),"register.password.not.match");
		Administrator admin = this.create();
		admin.setUserAccount(registerForm.getUserAccount());
		admin.setEmail(registerForm.getEmail());
		admin.setName(registerForm.getName());
		admin.setSurnames(registerForm.getSurnames());
		
		return admin;
	}
	
	// Other business methods

}
